from io import BytesIO

import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimSun']
plt.rcParams['axes.unicode_minus'] = False  # 可选设置,坐标轴负号
# 修改默认绘图参数
plt.rcParams["axes.facecolor"] = "#0080FF"
plt.rcParams["figure.facecolor"] = "#0080FF"
plt.rc('xtick', color='white')
plt.rc('ytick', color='white')
plt.rcParams['text.color'] = 'white'


def plot(df,title='',xlable='',ylable='',rotation=0,legend_switch=False,size=(6,2)):

    colors=['#FF7F00','#FFFF00']
    # 设置图形大小
    fig, ax = plt.subplots(figsize=size)
    if len(df.columns[1:])>3:
        ax = df.plot.bar(x=df.columns[0], y=df.columns[1+len(df.columns)//2:], color=colors, ax=ax)
        index2=df.columns[1:len(df.columns)//2+1]
        ## 添加文本
        for i,p in enumerate(ax.patches):
            ax.annotate(df.iloc[i//2].at[index2[i%2]][:-3], (p.get_x() + p.get_width() / 2, p.get_height()/2), ha='center',
                        va='center', xytext=(0, 10), textcoords='offset points',color='#000000')

    else:
        ax=df.plot.bar(x=df.columns[0],y=df.columns[1:],color=colors,ax=ax)

    plt.title(title)
    plt.xticks(rotation=rotation)
    plt.xlabel(xlable,color='white')
    plt.ylabel(ylable,color='white')
    ## 添加数字
    for p in ax.patches:
        ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2, p.get_height()), ha='center',
                    va='center', xytext=(0, 10), textcoords='offset points')

    #     ##柱状图中间的标签坐标
    # xticks = np.arange(len(x)) - width / 2
    # plt.xticks(xticks, x, rotation=rotation)

    # 获取当前轴对象
    # ax = plt.gca()
    ax.legend('lower center',ncol=len(df.columns[1:]), bbox_to_anchor=(1, -0.1))  # 设置图例为3列，并在 x 轴下方居中显示
    ax.legend().set_visible(legend_switch)
    # 隐藏上边框和右边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_color('white')
    ax.spines['left'].set_color('white')
    # ax.legend(ncol=len(df.columns[1:]), loc='lower center')  # 设置图例为3列，并在 x 轴下方居中显示
    # 调整x轴的框架大小
    plt.tight_layout()

    tmpfile = BytesIO()
    plt.savefig(tmpfile, format='png',dpi=100)
    tmpfile.seek(0)
    plt.show()
    return tmpfile

def barh(x,y,title,xlable='',ylable='',rotation=270):
    if len(x) !=len(y):
        raise Exception('x与y的长度不一致，无法画图')
    y=np.array(y)
    if len(y.shape) == 1:
        y = y.reshape((-1, 1))
    fig, ax = plt.subplots(figsize=(6, 2))
    colors=['#FF7F00','#FFFF00']
    # bar_colors = colors[:y.shape[1]] * len(x)  # 设置黄色柱子
    fig.set_facecolor('#0080FF')  # 设置蓝色背景
    width=0.1
    ## 画图
    for i in range(len(y[0])):
        plt.barh(x,y[:,i],color=colors[i])

        # 添加垂直虚线
        for j in np.arange(max(y)):
            plt.axvline(j+1, linestyle='--', color='white')
    plt.title(title)
    plt.xlabel(xlable,color='white')
    plt.ylabel(ylable,color='white')

    ## 添加数字
    for i in range(len(y[0])):
        for j in range(len(y[:,i])):
            plt.text(y[j,i]+max(y)/40,j+width*(i-len(y[0])/2),str(y[j,i]),ha='center', va='bottom')

    # 获取当前轴对象
    ax = plt.gca()

    # 隐藏上边框和右边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_color('white')
    ax.spines['left'].set_color('white')
    # 调整x轴的框架大小
    plt.tight_layout()
    tmpfile = BytesIO()
    plt.savefig(tmpfile, format='png',dpi=100)
    tmpfile.seek(0)
    plt.show()
    return tmpfile


def line(x,y,title,xlable='',ylable=''):
    if len(x) !=len(y):
        raise Exception('x与y的长度不一致，无法画图')
    fig, ax = plt.subplots(figsize=(6, 2))
    bar_colors = ['#FF7F00'] * len(x)  # 设置黄色柱子
    fig.set_facecolor('#0080FF')  # 设置蓝色背景
    plt.plot(x,y,color='#FF7F00')
    # # 添加垂直虚线
    for j in np.arange(len(x)):
        plt.axvline(j, linestyle='--', color='white')
    # 添加数字
    for i in range(len(x)):
        plt.text(i+0.05, y[i]+5, str(y[i]), ha='center', va='bottom')

    # 获取当前轴对象
    ax = plt.gca()

    # 隐藏上边框和右边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_color('white')
    ax.spines['left'].set_color('white')
    plt.title(title,color='white')
    plt.xlabel(xlable,color='white')
    plt.ylabel(ylable,color='white')
    tmpfile = BytesIO()
    plt.savefig(tmpfile, format='png',dpi=100)
    tmpfile.seek(0)
    plt.show()
    return tmpfile

def pie(labels,size,title):
    fig, ax = plt.subplots(figsize=(6, 3))
    fig.set_facecolor('#0080FF')  # 设置蓝色背景
    ax.pie(size,autopct='%1.1f%%')
    ax.set_title(title)
    ax.legend(loc='right',labels=labels,bbox_to_anchor=(1.75,0.5))
    tmpfile = BytesIO()
    plt.savefig(tmpfile, format='png')
    tmpfile.seek(0)
    plt.show()
    return tmpfile

# def table():
#     table = doc.add_table(df.shape[0] + 1, df.shape[1])
#     #
#     # # 填充表头
#     # for i, column_name in enumerate(df.columns):
#     #     table.cell(0, i).text = column_name
#     #
#     # # 填充数据
#     # for row in range(df.shape[0]):
#     #     for col in range(df.shape[1]):
#     #         table.cell(row + 1, col).text = str(df.iloc[row, col])
